<template>
	<div>
		<h2>修改密码</h2>
		<Form ref="form" :model="form" :rules="rules" label-position="top" class="ivu-mt">
			<Row type="flex" :gutter="48">
				<Col :span="8">
				<FormItem label="姓名">
					<Input v-model="info.name" readonly />
				</FormItem>
				<FormItem label="用户名">
					<Input v-model="info.phoneNo" readonly />
				</FormItem>
				<FormItem label="旧密码" prop="lastPassword">
					<Input v-model="form.lastPassword" type="password" placeholder="请输入旧密码" />
				</FormItem>
				<FormItem label="新密码" prop="newPassword">
					<Input v-model="form.newPassword" type="password" placeholder="请输入新密码" />
				</FormItem>
				<FormItem label="确认密码" prop="confirmPassword">
					<Input v-model="form.confirmPassword" type="password" placeholder="请确认新密码" />
				</FormItem>
				<FormItem>
					<Button type="primary" @click="onSubmit" :loading="loading">
						<span v-if="!loading">确认修改</span>
						<span v-else>修改中...</span>
					</Button>
				</FormItem>
				</Col>
			</Row>
		</Form>
	</div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
import { modifyPassword } from '@/api/user'

export default {
	name: 'password',
	data() {
		return {
			form: {
				lastPassword: '',
				newPassword: '',
				confirmPassword: ''
			},
			rules: {
				lastPassword: [{ required: true, message: '请输入旧密码' }],
				newPassword: [{ required: true, message: '请输入新密码' }],
				confirmPassword: [{ required: true, message: '请确认新密码' }]
			},
			loading: false
		}
	},
	computed: {
		...mapState('admin/user', [
			'info'
		]),
		...mapState('admin/layout', [
			'isMobile',
			'logoutConfirm'
		]),
	},
	methods: {
		...mapActions('admin/account', [
			'logout'
		]),
		onSubmit() {
			this.$refs.form.validate(async (valid) => {
				if (valid) {
					if (this.validateForm()) {
						this.loading = true;
						await modifyPassword({
							lastPassword: this.form.lastPassword,
							newPassword: this.form.newPassword
						})
						this.loading = false;
						this.$Message.success('修改密码成功，请重新登录');
						this.logout({
							confirm: false,
							vm: this
						});
					}
				}
			});
		},
		validateForm() {
			if (this.form.newPassword.length < 6) {
				this.$Message.warning('新密码位数不能少于6位')
				return false
			}
			if (this.form.confirmPassword.length < 6) {
				this.$Message.warning('确认密码位数不能少于6位')
				return false
			}
			if (this.form.newPassword !== this.form.confirmPassword) {
				this.$Message.warning('新密码与确认密码不同')
				return false
			}
			if (this.form.newPassword === this.form.lastPassword) {
				this.$Message.warning('新密码与旧密码相同')
				return false
			}
			return true
		}
	}
}
</script>
